package com.hdjk.view.activity.personalcenter;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.config.Constant;
import com.hdjk.view.dialog.EditTextPwdDialog;
import com.hdjk.view.dialog.MyAlertDialog;
import com.hdjk.view.entity.BankEntity;
import com.hdjk.view.entity.PayMethodEntity;
import com.hdjk.view.network.Network;
import com.hdjk.view.network.TransactionNetWork;
import com.hdjk.view.network.WalletNetWork;
import com.hdjk.view.util.SharedPreferencesUtil;
import com.hdjk.view.util.StringAppUtil;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.entity.Msg;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by sxy on 2018/1/4.
 */

public class WalletRechargeActivity extends BaseActivity implements View.OnClickListener {
    private PayMethodEntity mPayMethod;
    private List<BankEntity> bankList;
    private int bankIndex = 0;
    private int payMethod = 0;
    private MyAlertDialog alertDialog;

    // Content View Elements
    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private RelativeLayout rel_payment;
    private TextView tv_zf;
    private TextView tv_bank_name;
    private TextView tv_bank_number;
    private EditText et_money;
    private TextView tv_recharge;
    // End Of Content View Elements

    private void bindViews() {
        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        rel_payment = (RelativeLayout) findViewById(R.id.rel_payment);
        tv_zf = (TextView) findViewById(R.id.tv_zf);
        tv_bank_name = (TextView) findViewById(R.id.tv_bank_name);
        tv_bank_number = (TextView) findViewById(R.id.tv_bank_number);
        et_money = (EditText) findViewById(R.id.et_money);
        tv_recharge = (TextView) findViewById(R.id.tv_recharge);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_wallet_recharge);
        bindViews();
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        tv_recharge.setOnClickListener(this);
        rel_payment.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        getPayMethod();
    }
    private void getPayMethod() {
        mDialog.show();
        JSONObject object = new JSONObject();
        try {
            object.put("accountNumber", UserTokenUtil.getUserName(WalletRechargeActivity.this));
            TransactionNetWork.getPayMethod(UserTokenUtil.getToken(WalletRechargeActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.cancel();
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof PayMethodEntity) {
                        mPayMethod = (PayMethodEntity) msg.getData();
                        if (mPayMethod.getInvestorBankDetails() != null && mPayMethod.getInvestorBankDetails().getData() != null && mPayMethod.getInvestorBankDetails().getData().size() > 0) {
                            for (int i=0;i<mPayMethod.getInvestorBankDetails().getData().size();i++){
                                if (mPayMethod.getInvestorBankDetails().getData().get(i).getPreferred().equals("Y")){
                                    setPayMethod(payMethod, mPayMethod.getInvestorBankDetails().getData().get(i).getInvestorPayId());
                                }
                            }
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setPayMethod(int type, String investorPayId) {
        if (mPayMethod != null) {
            if (type == 0) {//银行卡
                if (mPayMethod.getInvestorBankDetails() != null && mPayMethod.getInvestorBankDetails().getData() != null && !TextUtils.isEmpty(investorPayId)) {
                    for (int i = 0; i < mPayMethod.getInvestorBankDetails().getData().size(); i++) {
                        if (investorPayId.equals(mPayMethod.getInvestorBankDetails().getData().get(i).getInvestorPayId()))
                            bankIndex = i;
                    }
                    String number = mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankNumber();
                    if (!TextUtils.isEmpty(number)) {
                        if (number.length() > 4) {
                            tv_bank_number.setText("***" + number.substring(number.length() - 4));
                        } else {
                            tv_bank_number.setText("***" + number);
                        }
                    }
                    bankList = SharedPreferencesUtil.getBankList(WalletRechargeActivity.this);
                    if (bankList == null || bankList.size() == 0) {
                        Network.getBankList(UserTokenUtil.getToken(WalletRechargeActivity.this), new CallBackListener() {
                            @Override
                            public void onCallBackCompleted(Msg msg) {
                                if (msg != null) {
                                    if (msg.getSuccess()) {
                                        if (!TextUtils.isEmpty(msg.getResult()))
                                            SharedPreferencesUtil.saveBankList(WalletRechargeActivity.this, msg.getResult());
                                        bankList = (List<BankEntity>) msg.getData();
                                        for (int i = 0; i < bankList.size(); i++) {
                                            if (bankList.get(i).getBankCode().equals(mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankCode())) {
                                                tv_bank_name.setText(bankList.get(i).getName());
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onCallBackError(Msg msg) {
                                mDialog.cancel();
                            }
                        });
                    } else {
                        for (int i = 0; i < bankList.size(); i++) {
                            if (bankList.get(i).getBankCode().equals(mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankCode())) {
                                tv_bank_name.setText(bankList.get(i).getName());
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tvNavBack:
                back();
                break;
            case R.id.rel_payment:
                Intent intent = new Intent(this, SelectPaymentActivity.class);
                intent.putExtra("isWallet",true);
                startActivityForResult(intent, 61);
                break;
            case R.id.tv_recharge:
                final String money=et_money.getText().toString();
                if (TextUtils.isEmpty(money)){
                    ToastUtils.showShortToast(this,"请输入充值金额");
                    return;
                }
                EditTextPwdDialog dialog = new EditTextPwdDialog(this, "输入密码", "", getResources().getDrawable(R.drawable.icon_input_pwd), "请输入交易密码", new EditTextPwdDialog.OnSureClickListener() {
                    @Override
                    public void onSureClick(String txt) {
                        mDialog.show();
                        JSONObject object = new JSONObject();
                        try {
                            object.put("accountNumber", UserTokenUtil.getUserName(WalletRechargeActivity.this));
                            object.put("currency", "156");
                            object.put("investorPayId", mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getInvestorPayId());
                            object.put("investmentAmount", money);
                            object.put("password", txt);
                            object.put("merchantNumber", StringAppUtil.getMerchantNumber());
                            object.put("payMethod", 0);
                            WalletNetWork.rechargeWallet(UserTokenUtil.getToken(WalletRechargeActivity.this), object.toString(), new CallBackListener() {
                                @Override
                                public void onCallBackCompleted(Msg msg) {
                                    mDialog.cancel();
                                    String title="";
                                    if (msg != null && msg.getSuccess()) {
                                        if (msg.getData()!=null){
                                            if ("failure".equals(msg.getData())||"void".equals(msg.getData())){
                                                title = "充值失败";
                                            }else {
                                                title = "充值成功";
                                                Intent intent=new Intent(Constant.INTENT_FILTER_STRING_AFTER_WALLET_EDIT);
                                                sendBroadcast(intent);
                                                setResult(333);
//                                                back();
                                            }
                                        }
                                    } else {
                                        if (TextUtils.isEmpty(msg.getMsg())) {
                                            title = "充值失败";
                                        } else {
                                            title =msg.getMsg();
                                        }
                                    }
                                    final String finalTitle = title;
                                    alertDialog = new MyAlertDialog(WalletRechargeActivity.this, title, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            if (finalTitle.equals("充值成功")) {
                                                back();
                                            }
                                        }
                                    });
                                    if (alertDialog != null)
                                        alertDialog.show();
//                                    ToastUtils.showShortToast(WalletRechargeActivity.this,title);
                                }

                                @Override
                                public void onCallBackError(Msg msg) {
                                    mDialog.cancel();
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                dialog.show();
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 61 && resultCode == 61) {
            String investorPayId = "";
            payMethod = data.getIntExtra("payMethod", -1);
            if (payMethod == 0) {
                investorPayId = data.getStringExtra("investorPayId");
            }
            if (payMethod >= 0) {
                setPayMethod(payMethod, investorPayId);
            }
        }
    }
}
